package com.gyg.程序员面试金典;

/**
 * 面试题 01.06. 字符串压缩
 */
public class T01_06 {
    /**
     * 面试题 01.06. 字符串压缩
     *
     * @param S
     * @return
     */
    public String compressString(String S) {
        /**
         if (S.equals("")){
         return  "";
         }
         String result = "";
         char nowStr = S.charAt(0);
         int count = 1;

         for (int i = 1; i < S.length(); i++) {
         if (nowStr == S.charAt(i)){
         count++;
         }else {
         result += nowStr  + "" + count;
         nowStr = S.charAt(i);
         count = 1;
         }

         }
         result += nowStr  + "" + count;
         return result.length() < S.length() ? result : S;

         */
        char[] chars = S.toCharArray();
        if (S.length() == 0) {
            return "";
        }
        StringBuilder ans = new StringBuilder("");
        int temp = 0, nowCont = 0;
        while (nowCont < S.length()) {
            if (nowCont == S.length() - 1) {
                ans.append(chars[temp]).append(nowCont - temp);
            } else if (chars[temp] != chars[nowCont]) {
                ans.append(chars[temp]).append(nowCont - temp);
                temp = nowCont;
            }
            nowCont++;
        }
        return ans.length() < S.length() ? ans.toString() : S;
    }
}
